<template>
  <el-dialog v-model="EditdialogForm" title="用户管理-编辑" width="500">
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="菜单名称" :label-width="formLabelWidth" prop="text">
        <el-input v-model="form.text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="菜单链接" :label-width="formLabelWidth" prop="url">
        <el-input v-model="form.url" autocomplete="off" />
      </el-form-item>
      <el-form-item label="菜单图标" :label-width="formLabelWidth" prop="icon">
        <el-input v-model="form.icon" autocomplete="off" />
      </el-form-item>
      <el-form-item label="菜单顺序" :label-width="formLabelWidth" prop="order">
        <el-input v-model="form.order" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="EditdialogForm = false">关闭</el-button>
        <el-button type="primary" @click="dialogsubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from "vue";
import { ElMessage } from "element-plus";
import http from "../../../../util/http.js";

const props = defineProps({
  pid: {
    type: String,
    value: null,
  },
  data: {
    type: Object,
    value: null,
  },
});

const emits = defineEmits(["refreshTable"]);

const form = ref({
  text: "",
  url: "",
  icon: "",
  pid: "",
  order: "",
});

watch(
  () => props.data,
  (newData) => {
    if (newData) {
      form.value = { ...newData }; // 将 props.data 的值赋给 form
    }
  },
  { immediate: true }
);

const rules = {
  text: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
  url: [{ required: true, message: "菜单链接不能为空", trigger: "blur" }],
  icon: [{ required: true, message: "菜单图标不能为空", trigger: "blur" }],
  order: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
};

const EditdialogForm = ref(false);
const formRef = ref(null);

const dialogsubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      form.value.pid = props.pid;
      http
        .post("/menu/edittable", form.value)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("修改成功");
            emits("refreshTable");
            EditdialogForm.value = false;
          } else {
            ElMessage.error("修改失败");
          }
        })
        .catch((error) => {
          ElMessage.error("请求失败");
          console.error(error);
        });
    } else {
      ElMessage.error("请完整填写表单");
    }
  });
};

const formLabelWidth = "140px";

defineExpose({
  EditdialogForm,
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
